<?php

namespace StudyBuddy\Modules\Observers;

use \StudyBuddy\Utf8String;
use \StudyBuddy\Twitter;
use \StudyBuddy\Tweet;
use \StudyBuddy\Bitly;

/**
 * This observer will post a tweet to Twitter API
 * In case of Question it will prefix some prefix like
 * #question + title + link + via @ourtwitter
 * It will test the length of title and will not add
 * prefix and not add @ourtwitter if that would cause
 * tweet to go over 140
 * It will truncate title if title is
 * already over 140
 *
 * In case of answer it will prefix I answered: $title + link
 *
 * It will try to use bit.ly shortener is it's setup
 * in !config.ini or will use our own domain/q/$id/#ans$aid
 *  It's always best to setup bit.ly api to get
 *  shorter url
 *
 */
class PostTweet extends \StudyBuddy\Observer {

    protected $text;
    protected $link;

    public function main() {
        d('get event: ' . $this->eventName);
        $a = $this->oRegistry->Request->getArray();
        if (empty($a['tweet'])) {
            d('tweet checkbox not checked');
            /**
             * Set the preference in Viewer object
             * for that "Post to Twitter" checkbox to be not checked
             * This is just in case it was checked before
             */
            $this->oRegistry->Viewer['b_tw'] = false;
            return;
        }

        /**
         * First if this site does not have support for Twitter API
         * OR if User does not have Twitter credentials then
         * there is nothing to do here
         * This is unlikely because user without Twitter credentials
         * will not get to see the checkbox to post to Twitter
         * but still it's better to check just to be sure
         */
        if (!extension_loaded('oauth')) {
            d('oauth extension not present');
            return;
        }

        try {
            $aTW = $this->oRegistry->Ini->getSection('TWITTER');
            if (empty($aTW) || empty($aTW['TWITTER_OAUTH_KEY']) || empty($aTW['TWITTER_OAUTH_SECRET'])) {
                d('Twitter API not enabled on this site');
                return;
                ;
            }
        } catch (\StudyBuddy\IniException $e) {
            d($e->getMessage());
            return;
        }

        if ('' === (string) $this->oRegistry->Viewer->getTwitterSecret()) {
            d('User does not have Twitter token');
            return;
        }

        /**
         * Now we know that user checked that checkbox
         * to Tweet content
         * and we now going to save this preference
         * in User object
         *
         */
        $this->oRegistry->Viewer['b_tw'] = true;

        switch ($this->eventName) {
            case 'onNewQuestion':
            case 'onNewAnswer':
                $this->tweet();
                break;
        }
    }

    /**
     * Post a Tweet with link to this
     * question
     */
    protected function tweet() {

        try {
            $reward = \StudyBuddy\Points::SHARED_CONTENT;
            $User = $this->oRegistry->Viewer;
            $oTweet = new Tweet();
            $oBitly = new Bitly($this->oRegistry->Ini->getSection('BITLY'));
            $oTwitter = new Twitter($this->oRegistry);
            $oResource = $this->obj;
            $Mongo = $this->oRegistry->Mongo;
            d('cp');
        } catch (\Exception $e) {
            d('Unable to post tweet because of this exception: ' . $e->getMessage() . ' in file: ' . $e->getFile() . ' on line: ' . $e->getLine());
            return;
        }

        $func = function() use ($oTweet, $oBitly, $oTwitter, $oResource, $User, $reward, $Mongo) {
                    $result = $oTweet->post($oTwitter, $oBitly, $oResource);
                    if (!empty($result) && is_array($result)) {

                        /**
                         * If status is OK (Tweet was posted)
                         * then reward the user with points!
                         */
                        if (!empty($result['id_str']) && ('200' == $result['http_code'])) {
                            $User->setReputation($reward);

                            /**
                             * Now need to also record Tweet Status data
                             * to TWEETS collection
                             */
                            try {
                                $coll = $Mongo->TWEETS;
                                $coll->ensureIndex(array('i_uid' => 1));

                                $tw_uid = (!empty($result['user']) && !empty($result['user']['id_str'])) ? $result['user']['id_str'] : null;
                                $tw_username = (!empty($result['user']) && !empty($result['user']['screen_name'])) ? $result['user']['screen_name'] : null;
                                /**
                                 * Record Tweet status to TWEETS collection.
                                 * Later can query Twitter to find
                                 * replies to these Tweets and add them
                                 * as "comments" to this Question or Answer
                                 *
                                 * HINT: if i_rid !== i_qid then it's an ANSWER
                                 * if these are the same then it's a Question
                                 * @var array
                                 */
                                $aData = array(
                                    '_id' => $result['id_str'],
                                    'i_uid' => $User->getUid(),
                                    'i_rid' => $oResource->getResourceId(),
                                    'i_qid' => $oResource->getQuestionId(),
                                    'tw_user_id_str' => $tw_uid,
                                    'tw_username' => $tw_username,
                                    'i_ts' => time(),
                                    'h_ts' => date('r')
                                );

                                $coll->save($aData);
                            } catch (\Exception $e) {
                                if (function_exists('e')) {
                                    e('Unable to save data to TWEETS collection because of ' . $e->getMessage() . ' in file: ' . $e->getFile() . ' on line: ' . $e->getLine());
                                }
                            }
                        }
                    }
                };
        d('cp');

        \StudyBuddy\runLater($func);
    }

}
